import Compressor from 'compressorjs'
import { showLoadingToast, closeToast } from 'vant'

export function convertImg(file) {
    showLoadingToast({
        duration: 0,
        message: '处理中...'
    })
    return new Promise((resolve, reject) => {
        blobToBase64(file).then(base64 => {
            file.base64 = base64
            getImage(base64).then(res => {
                file.width = res.width
                file.height = res.height
                var canvas = document.createElement('canvas')
                let image = new Image() //新建一个img标签（还没嵌入DOM节点)
                image.src = file.base64 //将图片的路径设成file路径   // 原图片
                var ctx = canvas.getContext('2d')
                let num = 0
                let maxWH = res.width > res.height ? res.width : res.height

                num = Math.floor(maxWH / 2000)
                canvas.width = res.width / (num || 1)
                canvas.height = res.height / (num || 1)

                ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
                // console.log(canvas.toDataURL())
                // form.value.idCardFront = canvas.toDataURL()
                dataURLToBlob(canvas.toDataURL()).then(fileAfter => {
                    // console.log(fileAfter, '这是修改后的file文件')
                    // console.log(fileAfter.size, '这是修改后的file文件大小')
                    new Compressor(fileAfter, {
                        quality: qualityCompute(fileAfter.size / 1024),
                        convertSize: 307200, // 300kb以下进行压缩
                        success(result) {
                            console.log(qualityCompute(fileAfter.size / 1024))
                            // console.log(result, '这是压缩后的result文件')
                            // console.log(result.size, '这是压缩后的result文件大小')
                            closeToast()
                            blobToBase64(result)
                                .then(base64Data => {
                                    resolve(base64Data)
                                    closeToast()
                                })
                                .catch(error => {
                                    console.error(error)
                                    closeToast()
                                })
                        },
                        error(err) {
                            console.log(err.message)
                            closeToast()
                        }
                    })
                })
            })
        })
    })
}

function qualityCompute(size) {
    if (size < 300) {
        return 0.9
    }
    if (size < 400) {
        return 0.5
    }
    if (size < 1000) {
        return 0.4
    }
    if (size < 2000) {
        return 0.2
    }
    if (size < 3000) {
        return 0.1
    }
    return 0.08
}

function dataURLToBlob(data) {
    return new Promise(resolve => {
        // 将base64 的图片转换成file对象上传 atob将ascii码解析成binary数据
        let binary = atob(data.split(',')[1])
        let mime = data.split(',')[0].match(/:(.*?);/)[1]
        let array = []
        for (let i = 0; i < binary.length; i++) {
            array.push(binary.charCodeAt(i))
        }
        let fileData = new Blob([new Uint8Array(array)], {
            type: mime
        })
        let file = new File([fileData], `${new Date().getTime()}.png`, {
            type: mime
        })
        resolve(file)
    })
}
function blobToBase64(blob) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onloadend = () => {
            resolve(reader.result)
        }
        reader.onerror = () => {
            reject(new Error('转换失败'))
        }
        reader.readAsDataURL(blob)
    })
}
function getImage(result) {
    return new Promise(function (resolve, reject) {
        let img = new Image()
        img.src = result
        img.onload = function () {
            //注意只有onload以后才可以拿到图片信息
            resolve({
                width: img.width,
                height: img.height
            })
        }
    })
}
